package us.versus.them.b3ge.character;

import flash.display.Sprite;
import flash.geom.Point;

import flash.events.MouseEvent;
import flash.events.Event;

import hxjson2.JSON;

import us.versus.them.b3ge.Util;

class Character extends Sprite {
	public var actions:Actions;
	public var position:Point;

	public var feet:Point;
	public var goal:Point;

	public function new( ?width=256, ?height=256 ) {
		super();
		this.position = new Point();
		this.addChild( this.actions = new Actions( width, height ) );

		// FIXME: don't hard code junk like this!
		this.feet = new Point( 42, 164 );
	}

	public function parse( json:String ) {
		this.init( JSON.decode( json ) );
	}

	public function init( config:Dynamic ) {
		try {
			var name = cast( config.name, String );
			for ( action in cast( config.actions, Array< Dynamic > ) ) {
				var sheet = "ResourcesCharactersSheets" + name + "" + action.name;
				var pts = new Array< Point >();
				
				var offsets :Array<Dynamic> = action.offsets;
				if ( null != offsets ) {
					for ( offset in offsets ) {
						pts.push( new Point( offset.x, offset.y ) );
					}
				}
				this.actions.add(
					  action
					, Util.bitmapDataForName( sheet )
					, pts
				);
			}
		} catch ( e:Dynamic ) {
			trace( 'oops:' + e );
		}
	}

	public function setGoal( goal:Point ) {
		this.actions.towards( this.position, ( this.goal = goal ) );
	}

	public function move() {
		if ( null == this.goal ) {
			this.actions.move(); // hopefully this is milling about
			return;
		} 
		if ( this.actions.towards( this.position, this.goal ) ) {
			this.actions.move();
			// TODO: check against world
			if ( null != this.actions.offset ) {
				var add = this.actions.offset();
				this.position.x += add.x;
				this.position.y += add.y;
			}
		}
	}
}
